package com.easpeed.elevator.utils;

import android.app.Dialog;
import android.content.Context;
import android.content.res.ColorStateList;
import android.os.Build;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import com.bigyu.utils.Logger;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ScreenUtils;
import com.easpeed.elevator.R;

import org.xmlpull.v1.XmlPullParser;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

public class NoticeDialog extends Dialog {
    private final String TAG = "NoticeDialog";

    private Context mContext;

    private Map<Integer, View.OnClickListener> onClickListenerMap = new HashMap<>();
    private Map<Integer, String> textMap = new HashMap<>();
    private Map<Integer, String> textHintMap = new HashMap<>();
    private Map<Integer, Integer> visiableMap = new HashMap<>();
    private Map<Integer, Integer> imageViewMap = new HashMap<>();
    private Map<Integer, Integer> textColorMap = new HashMap<>();
    private Map<Integer, Integer> viewBg = new HashMap<>();

    private Map<Integer, View> subView = new HashMap<>();

    private int defaultWidth = 0;
    private int defaultHeight = 0;
    private boolean cancel = true;
    private boolean canCancel = true;

    private int resId = R.layout.by_show_notice;
    private int style;

    private int maxHeight = 0;
    private View maxViewHeight;


    /**
     * 点击按钮关闭dialog
     */
    private boolean clickBtnCloseDialog = true;

    private float dimAmount = 0f;
    private int animalStyle;
    private int gravity = Gravity.CENTER;

    public void setGravity(int gravity) {
        this.gravity = gravity;
        Window dialogWindow = getWindow();
        hideBottomLine(dialogWindow);
        if (dialogWindow != null) {
            dialogWindow.setGravity(gravity);//设置dialog显示居中
        }
    }

    public void setWidth(int width) {
        WindowManager.LayoutParams lp = Objects.requireNonNull(getWindow()).getAttributes();
        lp.width = width;
        getWindow().setAttributes(lp);
    }

    public void setWindowAnimations(int style) {
        if (style == 0) {
            return;
        }
        Window dialogWindow = getWindow();
        if (dialogWindow != null) {
            dialogWindow.setWindowAnimations(style);
        }
    }

    /**
     * 是否全屏（去掉下面的白条）
     */
    private boolean isFullScreen;

    private NoticeDialog(Context context, int style) {
        super(context, style);
        this.style = style;
        init(context);
    }

    private NoticeDialog(Context context) {
        super(context);
        init(context);
    }


    private void init(Context context) {
        this.mContext = context;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setWindowAnimations(animalStyle);
        super.onCreate(savedInstanceState);
        setGravity(gravity);
        //dialogWindow.setWindowAnimations();设置动画效果
        setContentView(resId);
        setMaxHeight(maxHeight, maxViewHeight);
        setDialogWith(defaultWidth);
        setCanceledTouchOutside(cancel);
        setCanCancelable(canCancel);

        initSubView();
        initListener();
        initText();
        initImageView();
        initVisibility();
        initTextColor();
        initViewbg();
        initHintText();
        if (dimAmount != 0) {
            setDialogDimAmount(dimAmount);
        }
    }

    private void initSubView() {
        Set<Integer> keySet = subView.keySet();
        for (Integer id : keySet) {
            addSubView(id, subView.get(id));
        }
    }


    public void addSubView(int id, View view) {
        if (findViewById(id) instanceof ViewGroup) {
            ((ViewGroup) findViewById(id)).addView(view);
        } else {
        }
    }


    public void setDialogWith(int width) {
        setDialogWith(width, 0);
    }

    public void setDialogWith(int width, int height) {
        WindowManager.LayoutParams lp = Objects.requireNonNull(getWindow()).getAttributes();
        if (width == 0) {
            lp.width = ScreenUtils.getScreenWidth() * 4 / 5;// 设置dialog宽度为屏幕的4/5
        } else {
            lp.width = width;
        }
        if (height == 0) {
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        } else {
            lp.height = height;
        }
        this.defaultWidth = lp.width;
        this.defaultHeight = lp.height;
        getWindow().setAttributes(lp);
    }

    public void setDialogDimAmount(float dimAmount) {
        WindowManager.LayoutParams lp = Objects.requireNonNull(getWindow()).getAttributes();
        lp.dimAmount = dimAmount;
        getWindow().setAttributes(lp);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }

    private void initViewbg() {
        Set<Integer> keySet = viewBg.keySet();
        for (Integer id : keySet) {
            setRootBg(id, viewBg.get(id));
        }
    }

    public void setHideBottomLine(boolean b) {
        isFullScreen = b;
    }

    private void hideBottomLine(Window dialogWindow) {
        if (!isFullScreen) {
            return;
        }
        //去掉底部菜单
        View decorView = dialogWindow.getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);
    }


    private void initImageView() {
        Set<Integer> keySet = imageViewMap.keySet();
        for (Integer id : keySet) {
            setImageView(id, imageViewMap.get(id));
        }
    }

    private void initTextColor() {
        Set<Integer> keySet = textColorMap.keySet();
        for (Integer id : keySet) {
            setTextColor(id, textColorMap.get(id));
        }
    }

    public void setMaxHeight(int height, View view) {
        this.maxHeight = height;
        this.maxViewHeight = view;
        addViewChangeListener(view);
    }

    private void addViewChangeListener(View view) {
        if (maxHeight != 0 && view != null) {
            view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    Logger.e(TAG, "onGlobalLayout: " + view.getHeight());

                    if (view.getHeight() > maxHeight) {
//                        setDialogWith(defaultWidth, maxHeight);
                        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
                        layoutParams.height = maxHeight;
                        view.setLayoutParams(layoutParams);
                    } else {
                        setDialogWith(defaultWidth);
                    }
                }
            });
        }
    }


    private void setCanCancelable(boolean cancel) {
        setCancelable(cancel);
    }

    private void initVisibility() {
        Set<Integer> keySet = visiableMap.keySet();
        for (Integer id : keySet) {
            setVisibility(id, visiableMap.get(id));
        }
    }

    private void initText() {
        Set<Integer> keySet = textMap.keySet();
        for (Integer id : keySet) {
            setText(id, textMap.get(id));
        }
    }

    private void initHintText() {
        Set<Integer> keySet = textHintMap.keySet();
        for (Integer id : keySet) {
            setHintText(id, textHintMap.get(id));
        }
    }

    private void initListener() {
        Set<Integer> keySet = onClickListenerMap.keySet();
        for (Integer id : keySet) {
            setOnclickListener(id, onClickListenerMap.get(id));
        }
    }


    public void setOnclickListener(int id, View.OnClickListener l) {
        View view = findViewById(id);
        if (view != null) {
            view.setOnClickListener(v -> {
                if (clickBtnCloseDialog) {
                    dismiss();
                }
                l.onClick(v);
            });
        }
    }

    public void setClickBtnDismissDialog(boolean b) {
        this.clickBtnCloseDialog = b;
    }

    /**
     * @param id 根据id返回控件对象
     * @return view对象
     */
    public View getView(int id) {
        return findViewById(id);
    }

    public String getText(int id) {
        if (findViewById(id) instanceof TextView) {
            return ((TextView) findViewById(id)).getText().toString();
        }
        return null;
    }

    /**
     * @param id 根据id返回控件对象
     * @return view对象
     */
    public <T> T getViewT(int id) {
        return (T) getView(id);
    }


    public void setRootBg(int id, int bg) {
        findViewById(id).setBackgroundResource(bg);
    }

    public void setVisibility(int id, int visibility) {
        findViewById(id).setVisibility(visibility);
    }

    public void setActivated(int id, boolean visibility) {
        findViewById(id).setActivated(visibility);
    }

    public boolean getActivated(int id) {
        return findViewById(id).isActivated();
    }


    public void setText(int id, String text) {
        if (findViewById(id) instanceof TextView) {
            ((TextView) findViewById(id)).setText(text);
        }
    }

    public  void setEnable(int id, boolean enable) {
        findViewById(id).setEnabled(enable);
    }

    public void setHintText(int id, String text) {
        if (findViewById(id) instanceof TextView) {
            ((TextView) findViewById(id)).setHint(text);
        }
    }

    public void setImageView(int id, int iconId) {
        if (findViewById(id) instanceof ImageView) {
            ((ImageView) findViewById(id)).setImageResource(iconId);
        }
    }

    public void setTextColor(int id, int iconId) {
        if (findViewById(id) instanceof TextView) {
            try {
                XmlPullParser xrp = mContext.getResources().getXml(iconId);
                ColorStateList csl = ColorStateList.createFromXml(mContext.getResources(), xrp);
                ((TextView) findViewById(id)).setTextColor(csl);
            } catch (Exception e) {
                try {
                    ((TextView) findViewById(id)).setTextColor(mContext.getResources().getColor(iconId));
                } catch (Exception e1) {
                    ((TextView) findViewById(id)).setTextColor(iconId);
                }
            }
        }
    }

    public void setText(int id, SpannableString text) {
        if (findViewById(id) instanceof TextView) {
            ((TextView) findViewById(id)).setMovementMethod(LinkMovementMethod.getInstance());
            ((TextView) findViewById(id)).setText(text);
        }
    }


    public void setCanceledTouchOutside(Boolean b) {
        setCanceledOnTouchOutside(b);//点击外部Dialog消失
    }

    public static class BuilderDefaultNotice {
        private NoticeDialog dialog;

        public BuilderDefaultNotice(Context context, int style) {
            if (style == -1 || style == 0) {
                dialog = new NoticeDialog(context);
            } else {
                dialog = new NoticeDialog(context, style);
            }
        }

        public BuilderDefaultNotice(Context context) {
            dialog = new NoticeDialog(context, ConstDialogStyle.DEFAULT_STYLE);
        }

        public BuilderDefaultNotice setTitle(String title) {
            if (TextUtils.isEmpty(title)) {
                dialog.visiableMap.put(R.id.title, View.GONE);
            }
            dialog.textMap.put(R.id.title, title);
            return this;
        }

        public BuilderDefaultNotice setContent(String content) {
            dialog.textMap.put(R.id.content, content);
            return this;
        }

        public BuilderDefaultNotice setCancel(String text) {
            dialog.textMap.put(R.id.cancel, text);
            return this;
        }

        public BuilderDefaultNotice setSure(String text) {
            dialog.textMap.put(R.id.sure, text);
            return this;
        }

        public BuilderDefaultNotice setCancelListener(View.OnClickListener onClickListener) {
            dialog.onClickListenerMap.put(R.id.cancel, onClickListener);
            return this;
        }

        public BuilderDefaultNotice setSureListener(View.OnClickListener onClickListener) {
            dialog.onClickListenerMap.put(R.id.sure, onClickListener);
            return this;
        }

        public BuilderDefaultNotice create() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                dialog.create();
            }
            return this;
        }

        public BuilderDefaultNotice setCanCancel(boolean b) {
            dialog.canCancel = b;
            return this;
        }

        public BuilderDefaultNotice setHideBottomLine(boolean b) {
            dialog.isFullScreen = b;
            return this;
        }

        public BuilderDefaultNotice show() {
            dialog.show();
            return this;
        }

    }

    public static class Builder {
        private NoticeDialog dialog;

        public Builder(Context context, int style) {
            if (style == -1 || style == 0) {
                dialog = new NoticeDialog(context);
            } else {
                dialog = new NoticeDialog(context, style);
            }
        }

        public Builder(Context context) {
            dialog = new NoticeDialog(context, ConstDialogStyle.DEFAULT_STYLE);
        }


        public Builder setLayoutId(int resId) {
            dialog.resId = resId;
            return this;
        }

        public Builder addSubView(int id, View view) {
            dialog.subView.put(id, view);
            return this;
        }

        public Builder init() {
            return this;
        }

        public Builder setOnclickListener(int id, View.OnClickListener onClickListener) {
            dialog.onClickListenerMap.put(id, onClickListener);
            return this;
        }

        public Builder setCanceledOnTouchOutside(boolean b) {
            dialog.cancel = b;
            return this;
        }


        public Builder setClickBtnDismissDialog(boolean b) {
            dialog.clickBtnCloseDialog = b;
            return this;
        }

        public Builder setDimAmount(float dimAmount) {
            dialog.dimAmount = dimAmount;
            return this;
        }

        public Builder setDialogWidth(int b) {
            dialog.defaultWidth = b;
            return this;
        }

        public Builder setCanCancel(boolean b) {
            dialog.canCancel = b;
            return this;
        }

        public Builder setText(int id, String text) {
            dialog.textMap.put(id, text);
            return this;
        }

        public Builder setHintText(int id, String text) {
            dialog.textHintMap.put(id, text);
            return this;
        }

        public Builder setMaxHeight(int height, View view) {
            dialog.setMaxHeight(height, view);
            return this;
        }

        public Builder setTextColor(int id, int color) {
            dialog.textColorMap.put(id, color);
            return this;
        }

        public Builder setRootBg(int id, int bg) {
            dialog.viewBg.put(id, bg);
            return this;
        }

        public Builder setHideBottomLine(boolean b) {
            dialog.isFullScreen = b;
            return this;
        }

        public Builder setWindowAnimations(int style) {
            dialog.animalStyle = style;
            return this;
        }

        public NoticeDialog create() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                dialog.create();
            }
            return dialog;
        }

        public NoticeDialog show() {
            dialog.show();
            return dialog;
        }
    }
}
